<?php

namespace App\Http\Controllers;

use App\Models\School;
use Illuminate\Http\Request;

class ApiController extends Controller
{
    /**
     * 获取城市列表
     * /api/location
     * @return \Illuminate\Http\JsonResponse
     */
    public function location()
    {
        $data = [];
        $provinces = config('admin.location.province');
        foreach ($provinces as $province => $item) {
            $cities = (array)config('admin.location.city.' . $province);
            $c = [];
            foreach ($cities as $city => $v) {
                $c[] = $v;
            }
            $data[] = [
                'id' => $province,
                'name' => $item,
                'cities' => $c,
            ];
        }
        return response()->json($data);
    }

    /**
     * 获取学校列表
     * URL：/api/schools
     * name：学校名（支持模糊查询）
     * city：城市名（如：西安市）
     * province：省名（如：beijing）
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function schools(Request $request)
    {
        $school = $request->input('name');
        $city = $request->input('city');
        $province = $request->input('province');
        $schools = School::select(['name', 'city', 'province']);
        if (!empty($school)) {
            $schools = $schools->where('name', 'like', "%{$school}%");
        }
        if (!empty($city)) {
            $schools = $schools->where('city', $city);
        }
        if (!empty($province)) {
            $schools = $schools->where('province', $province);
        }
        $schools = $schools->get();
        return response()->json($schools);
    }
}
